from flask import Blueprint, render_template, request, jsonify
from flask_login import current_user
from sqlalchemy import desc

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.utils import validate
from applications.common.utils.http import success_api, fail_api, table_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Dept, User, CompanyJob, JobhunterToudi
from applications.schemas import DeptSchema
from applications.schemas.company_job import CompanyJobSchema
from applications.view.system.native_sql import NativeSQL

bp = Blueprint('company', __name__, url_prefix='/company')
user = 'lucas'
password = '5515612'
dbname = 'pearadminflask'
nativesql = NativeSQL(user, password, dbname)

# 职位管理
@bp.get('/')
@authorize("system:company:main")
def main():
    return render_template('system/company/main.html')

@bp.get('/data')
@authorize("system:company:main")
def data():
    jobname = str_escape(request.args.get('jobname', type=str))
    current_username = current_user.username
    print(current_username)
    sql = 'select b.role_id from admin_user a left join admin_user_role b on a.id = b.user_id where a.username = "{}"'.format(current_username)
    code, msg, data = nativesql.query(sql)
    print(code, msg, data)
    role_id = data[0]['role_id']
    if 3 == role_id:
        if jobname:
            resdata = CompanyJob.query.filter_by(username=current_username, jobname=jobname).layui_paginate()
        else:
            resdata = CompanyJob.query.filter_by(username=current_username).layui_paginate()
    else:
        if jobname:
            resdata = CompanyJob.query.filter_by(jobname=jobname).layui_paginate()
        else:
            resdata = CompanyJob.query.order_by(desc(CompanyJob.create_time)).layui_paginate()
    count = resdata.total
    print(resdata)
    return table_api(data= model_to_dicts(schema=CompanyJobSchema, data=resdata.items), count=count)

@bp.get('/add')
@authorize("system:company:add", log=True)
def add():
    return render_template('system/company/add.html')

@bp.post('/save')
@authorize("system:company:add", log=True)
def save():
    req_json = request.get_json(force=True)
    print(req_json)
    job = CompanyJob(jobname=str_escape(req_json.get('jobname')),
                     jobdesc=str_escape(req_json.get('jobdesc')),
                     education=str_escape(req_json.get('education')),
                     salary=str_escape(req_json.get('salary')),
                     company=str_escape(req_json.get('company')),
                     username=current_user.username,
                     status='待审核',
                     city=str_escape(req_json.get('city')))
    db.session.add(job)
    db.session.commit()
    return success_api(msg="增加成功")

@bp.delete('/remove/<int:id>')
@authorize("system:company:remove", log=True)
def delete(id):
    print(id)
    res = CompanyJob.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")

@bp.delete('/shenhe/<int:id>')
@authorize("system:company:shenhe", log=True)
def shenhe(id):
    print(id)
    data = {"status": '审核通过'}
    d = CompanyJob.query.filter_by(id=id).update(data)
    if not d:
        return fail_api(msg="审核失败")
    db.session.commit()
    return success_api(msg="审核成功")

@bp.delete('/toudi/<int:id>')
@authorize("system:company:toudi", log=True)
def toudi(id):
    print(id)
    sql = 'select count(*) as total from jobhunter_resume_tb where username = "{}"'.format(current_user.username)
    code, msg, data = nativesql.query(sql)
    if int(data[0]['total']) != 1:
        return fail_api(msg="投递失败，请确保有且只有一份简历")
    job = JobhunterToudi(username=current_user.username, jobid=id)
    db.session.add(job)
    db.session.commit()
    return success_api(msg="投递成功")
